<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>PBL需求管理系统</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link
          href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css"
          rel="stylesheet"
  />
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: "#165DFF",
            secondary: "#36D399",
            neutral: "#F3F4F6",
            dark: "#1F2937",
          },
          fontFamily: {
            inter: ["Inter", "sans-serif"],
          },
        },
      },
    };
  </script>
  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .bg-gradient-blue {
        background: linear-gradient(135deg, #165dff 0%, #0039cb 100%);
      }
      .shadow-card {
        box-shadow: 0 10px 25px -5px rgba(22, 93, 255, 0.1),
        0 8px 10px -6px rgba(22, 93, 255, 0.1);
      }
      .scale-hover {
        transition: transform 0.2s ease-in-out;
      }
      .scale-hover:hover {
        transform: scale(1.02);
      }
      .radio-dot {
        width: 18px;
        height: 18px;
        border-radius: 50%;
        border: 2px solid #9ca3af;
        transition: all 0.2s ease;
      }
      .radio-dot.active {
        border-color: #165dff;
        background-color: #165dff;
        box-shadow: 0 0 0 3px rgba(22, 97, 255, 0.2);
      }
      .dropdown-animate {
        animation: fadeIn 0.3s ease-in-out;
      }
      @keyframes fadeIn {
        from {
          opacity: 0;
          transform: translateY(-10px);
        }
        to {
          opacity: 1;
          transform: translateY(0);
        }
      }
      .tab-active {
        border-bottom: 2px solid #165dff;
        color: #165dff;
        font-weight: 500;
      }
    }
  </style>
  <style>
    /* 添加通知框样式 */
    .notification {
      position: fixed;
      top: 20px;
      right: 20px;
      padding: 16px 24px;
      background: #f6ffed;
      border: 1px solid #b7eb8f;
      border-radius: 8px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      display: flex;
      align-items: center;
      gap: 12px;
      z-index: 1000;
      opacity: 0;
      transform: translateX(100%);
      transition: all 0.3s ease-in-out;
    }

    .notification.show {
      opacity: 1;
      transform: translateX(0);
    }

    .notification .icon {
      color: #52c41a;
      font-size: 20px;
    }

    .notification .message {
      color: #52c41a;
      font-size: 14px;
      font-weight: 500;
    }

    .notification.error {
      background: #fff2f0;
      border-color: #ffccc7;
    }

    .notification.error .icon,
    .notification.error .message {
      color: #ff4d4f;
    }
  </style>
</head>
<body class="font-inter bg-gray-50 min-h-screen flex flex-col">
<!-- 主内容区 -->
<main class="flex-grow flex items-center justify-center p-4 sm:p-6 md:p-8">
  <div class="w-full max-w-md">
    <!-- 卡片 -->
    <div
            class="bg-white rounded-2xl shadow-card overflow-hidden scale-hover"
    >
      <!-- 卡片头部 -->
      <div class="bg-gradient-blue p-6 text-white">
        <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold mb-2">
          欢迎来到PBL需求管理系统
        </h2>
        <p class="text-white/80">请登录或注册您的账号</p>
      </div>

      <!-- 卡片内容 -->
      <div class="p-6">
        <!-- 登录方式切换 -->
        <div class="flex border-b">
          <button
                  id="codeLoginTab"
                  class="tab-active flex-1 py-3 text-center transition-colors"
          >
            验证码登录
          </button>
          <button
                  id="passwordLoginTab"
                  class="flex-1 py-3 text-center transition-colors"
          >
            密码登录
          </button>
        </div>

        <!-- 表单 -->
        <form id="loginForm" class="space-y-5">
          <!-- 手机号/邮箱 -->
          <div class="space-y-2">
            <label
                    for="account"
                    class="block text-sm font-medium text-gray-700"
            >手机号/邮箱</label
            >
            <div class="relative">
                  <span
                          class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-400"
                  >
                    <i class="fa-solid fa-user"></i>
                  </span>
              <input
                      type="text"
                      id="account"
                      name="account"
                      class="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary outline-none transition-all"
                      placeholder="请输入手机号或邮箱"
              />
            </div>
          </div>

          <!-- 验证码登录表单 -->
          <div id="codeLoginForm">
            <div class="space-y-2">
              <label
                      for="verificationCode"
                      class="block text-sm font-medium text-gray-700"
              >验证码</label
              >
              <div class="flex space-x-3">
                <div class="relative flex-grow">
                      <span
                              class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-400"
                      >
                        <i class="fa-solid fa-shield"></i>
                      </span>
                  <input
                          type="text"
                          id="verificationCode"
                          class="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary outline-none transition-all"
                          placeholder="请输入验证码"
                  />
                </div>
                <button
                        type="button"
                        id="getCodeBtn"
                        class="bg-primary hover:bg-primary/90 text-white px-4 py-3 rounded-lg whitespace-nowrap transition-all"
                >
                  获取验证码
                </button>
              </div>
            </div>
          </div>

          <!-- 密码登录表单 -->
          <div id="passwordLoginForm" class="hidden">
            <div class="space-y-2">
              <label
                      for="password"
                      class="block text-sm font-medium text-gray-700"
              >密码</label
              >
              <div class="relative">
                    <span
                            class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-400"
                    >
                      <i class="fa-solid fa-lock"></i>
                    </span>
                <input
                        type="password"
                        id="password"
                        name="password"
                        class="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary outline-none transition-all"
                        placeholder="请输入密码"
                />
                <button
                        type="button"
                        id="togglePassword"
                        class="absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400"
                >
                  <i class="fa-solid fa-eye"></i>
                </button>
              </div>
            </div>
            <div class="flex justify-between items-center">
              <label class="flex items-center">
                <input
                        type="checkbox"
                        class="text-primary focus:ring-primary/50 border-gray-300 rounded"
                />
                <span class="ml-2 text-sm text-gray-600">记住密码</span>
              </label>
              <a href="#" class="text-sm text-primary hover:underline"
              >忘记密码?</a
              >
            </div>
          </div>

          <!-- 登录按钮 -->
          <button
                  type="submit"
                  class="w-full bg-primary hover:bg-primary/90 text-white py-3 rounded-lg font-medium transition-all shadow-lg shadow-primary/20 hover:shadow-xl hover:shadow-primary/30"
          >
            登录/注册
          </button>

          <!-- 服务协议 -->
          <div class="flex items-start">
            <div class="flex items-center h-5">
              <input
                      id="agreement"
                      name="agreement"
                      type="checkbox"
                      class="h-4 w-4 text-primary focus:ring-primary/50 border-gray-300 rounded"
              />
            </div>
            <div class="ml-3 text-sm">
              <label for="agreement" class="text-gray-600"
              >我已阅读并同意<a
                      href="#"
                      class="text-primary hover:underline"
              >服务协议</a
              >和<a href="#" class="text-primary hover:underline"
              >隐私协议</a
              ></label
              >
            </div>
          </div>

          <!-- 用户类型选择 -->
          <div class="space-y-4">
            <label class="block text-sm font-medium text-gray-700">用户类型</label>

            <div class="grid grid-cols-1 gap-3">
              <!-- 专家 -->
              <div class="relative">
                <div
                        id="expertOption"
                        class="flex items-center p-4 border border-gray-200 rounded-lg cursor-pointer hover:border-primary/50 transition-all"
                >
                  <div class="radio-dot mr-3" id="expertDot"></div>
                  <div>
                    <h3 class="font-medium text-gray-900">专家</h3>
                    <p class="text-sm text-gray-500">提供专业解决方案</p>
                  </div>
                  <div class="ml-auto">
                    <i class="fa-solid fa-chevron-right text-gray-400"></i>
                  </div>
                </div>
              </div>

              <!-- 加载状态 -->
              <div id="loadingState" class="hidden text-center py-4">
                <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
                <p class="mt-2 text-gray-600">正在加载兴趣点...</p>
              </div>

              <!-- 兴趣点选择区域 -->
              <div id="interestTopicContainer" class="hidden mt-6">
                <h3 class="text-lg font-medium text-gray-900 mb-4">请选择您的兴趣点</h3>
                <div id="interestTopicList" class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3">
                  <!-- 兴趣点选项将在这里动态生成 -->
                </div>
                <div class="mt-6 flex justify-end">
                  <button id="confirmSelection" class="px-6 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors">
                    确认选择
                  </button>
                </div>
              </div>


              <!-- 发布方 -->
              <div class="relative">
                <div
                        id="publisherOption"
                        class="flex items-center p-4 border border-gray-200 rounded-lg cursor-pointer hover:border-primary/50 transition-all"
                >
                  <div class="radio-dot mr-3" id="publisherDot"></div>
                  <div>
                    <h3 class="font-medium text-gray-900">发布方</h3>
                    <p class="text-sm text-gray-500">
                      发布需求获取解决方案
                    </p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
</main>

<!-- 专家选项悬浮框 -->
<div
        id="expertPopup"
        class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4 hidden"
        style="display: none"
>
  <div
          class="bg-white rounded-xl shadow-xl w-full max-w-md overflow-hidden scale-hover"
  >
    <div class="bg-primary p-5 text-white">
      <div class="flex justify-between items-center">
        <h3 class="text-xl font-bold">专家信息</h3>
        <button id="closePopup" class="text-white/80 hover:text-white">
          <i class="fa-solid fa-times"></i>
        </button>
      </div>
    </div>
    <div class="p-5 space-y-4">
      <button
              class="w-full bg-primary hover:bg-primary/90 text-white py-3 rounded-lg font-medium transition-all shadow-lg shadow-primary/20"
      >
        确认
      </button>
    </div>
  </div>
</div>

<!-- 添加通知框HTML -->
<div class="notification">
  <span class="icon">✓</span>
  <span class="message"></span>
</div>

<script>
  // 获取DOM元素
  const expertOption = document.getElementById("expertOption");
  const publisherOption = document.getElementById("publisherOption");
  const expertDot = document.getElementById("expertDot");
  const publisherDot = document.getElementById("publisherDot");
  const expertPopup = document.getElementById("expertPopup");
  const closePopup = document.getElementById("closePopup");
  const getCodeBtn = document.getElementById("getCodeBtn");
  const codeLoginTab = document.getElementById("codeLoginTab");
  const passwordLoginTab = document.getElementById("passwordLoginTab");
  const codeLoginForm = document.getElementById("codeLoginForm");
  const passwordLoginForm = document.getElementById("passwordLoginForm");
  const togglePassword = document.getElementById("togglePassword");
  const passwordInput = document.getElementById("password");

  // 登录方式切换
  codeLoginTab.addEventListener("click", function () {
    codeLoginTab.classList.add("tab-active");
    passwordLoginTab.classList.remove("tab-active");
    codeLoginForm.classList.remove("hidden");
    passwordLoginForm.classList.add("hidden");
  });

  passwordLoginTab.addEventListener("click", function () {
    passwordLoginTab.classList.add("tab-active");
    codeLoginTab.classList.remove("tab-active");
    passwordLoginForm.classList.remove("hidden");
    codeLoginForm.classList.add("hidden");
  });

  // 密码显示/隐藏切换
  togglePassword.addEventListener("click", function () {
    const type =
            passwordInput.getAttribute("type") === "password"
                    ? "text"
                    : "password";
    passwordInput.setAttribute("type", type);
    this.innerHTML =
            type === "password"
                    ? '<i class="fa-solid fa-eye"></i>'
                    : '<i class="fa-solid fa-eye-slash"></i>';
  });

  // 专家选项点击事件
  expertOption.addEventListener("click", function () {
    // 激活专家单选框
    expertDot.classList.add("active");
    publisherDot.classList.remove("active");

    // 显示悬浮框
    expertPopup.classList.remove("hidden");
    expertPopup
            .querySelector(".dropdown-animate")
            .classList.add("dropdown-animate");
  });

  // 发布方选项点击事件
  publisherOption.addEventListener("click", function () {
    // 激活发布方单选框
    publisherDot.classList.add("active");
    expertDot.classList.remove("active");

    // 改变发布方选项样式
    publisherOption.classList.add("border-primary");
    publisherOption.classList.add("bg-primary/5");
  });

  // 关闭悬浮框
  closePopup.addEventListener("click", function () {
    expertPopup.classList.add("hidden");
  });

  // 点击空白处关闭悬浮框
  expertPopup.addEventListener("click", function (e) {
    if (e.target === expertPopup) {
      expertPopup.classList.add("hidden");
    }
  });

  // 验证码登录逻辑
  let countdown = 60;
  getCodeBtn.addEventListener("click", function () {
    const account = document.getElementById("account").value;
    if (!account) {
      showNotification("请输入手机号或邮箱", "error");
      return;
    }

    // 发送获取验证码请求
    fetch("/api/sendVerificationCode", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ account }),
    })
            .then((response) => response.json())
            .then((data) => {
              if (data.success) {
                // 验证码发送成功，开始倒计时
                this.disabled = true;
                this.textContent = `重新获取(${countdown}s)`;
                this.classList.add("bg-gray-400");
                this.classList.remove("bg-primary", "hover:bg-primary/90");

                const timer = setInterval(() => {
                  countdown--;
                  this.textContent = `重新获取(${countdown}s)`;

                  if (countdown <= 0) {
                    clearInterval(timer);
                    this.disabled = false;
                    this.textContent = "获取验证码";
                    this.classList.remove("bg-gray-400");
                    this.classList.add("bg-primary", "hover:bg-primary/90");
                    countdown = 60;
                  }
                }, 1000);
              } else {
                showNotification(data.message || "验证码发送失败", "error");
              }
            })
            .catch((error) => {
              showNotification("发送验证码请求出错，请稍后再试", "error");
            });
  });

  // 表单提交事件
  document
          .getElementById("loginForm")
          .addEventListener("submit", function (e) {
            e.preventDefault();

            // 获取当前登录方式
            const isCodeLogin = !codeLoginForm.classList.contains("hidden");

            // 简单验证
            const account = document.getElementById("account").value;
            const agreement = document.getElementById("agreement").checked;

            if (!account) {
              showNotification("请输入手机号或邮箱", "error");
              return;
            }

            //验证码登录逻辑
            if (isCodeLogin) {
              const verificationCode =
                      document.getElementById("verificationCode").value;
              if (!verificationCode) {
                showNotification("请输入验证码", "error");
                return;
              }

              // 获取选中的用户类型
              let userType = "";
              if (expertDot.classList.contains("active")) {
                userType = "expert";
              } else if (publisherDot.classList.contains("active")) {
                userType = "publisher";
              } else {
                showNotification("请选择用户类型", "error");
                return;
              }

              // 验证协议是否同意
              if (!agreement) {
                showNotification("请同意服务协议和隐私协议", "error");
                return;
              }

              // 发送验证码登录请求
              fetch("/api/verifyCodeLogin", {
                method: "POST",
                headers: {
                  "Content-Type": "application/json",
                },
                body: JSON.stringify({
                  account,
                  verificationCode,
                  userType,
                }),
              })
                      .then((response) => response.json())
                      .then((data) => {
                        if (data.success) {
                          if (data.user.usertype && data.user.usertype !== userType) {
                            // 如果数据库中的用户类型与选择的不同，发送更新请求
                            return fetch("/api/updateUserType", {
                              method: "POST",
                              headers: {
                                "Content-Type": "application/x-www-form-urlencoded",
                              },
                              body: `userId=${data.user.id}&newUserType=${userType}`,
                            }).then((response) => response.json());
                          }
                          return data;
                        } else {
                          throw new Error(data.message || "验证码验证失败");
                        }
                      })
                      .then((data) => {
                        if (data.success) {
                          // 登录成功，存储用户信息到本地存储
                          localStorage.setItem("user", JSON.stringify(data.user));
                          // 使用加密后的ID进行跳转
                          window.location.href = `/user/${data.encryptedId}/requirements`;
                        } else {
                          showNotification(data.message || "用户类型更新失败", "error");
                        }
                      })
                      .catch((error) => {
                        showNotification(
                                error.message || "登录请求出错，请稍后再试",
                                "error"
                        );
                      });
            } else {
              const password = document.getElementById("password").value;
              if (!password) {
                showNotification("请输入密码", "error");
                return;
              }

              // 密码登录逻辑
              if (!agreement) {
                showNotification("请同意服务协议和隐私协议", "error");
                return;
              }

              // 获取选中的用户类型
              let userType = "";
              if (expertDot.classList.contains("active")) {
                userType = "expert";
              } else if (publisherDot.classList.contains("active")) {
                userType = "publisher";
              } else {
                showNotification("请选择用户类型", "error");
                return;
              }

              // 发送登录请求到后端
              const formData = new FormData();
              formData.append("account", account);
              formData.append("password", password);

              fetch("/login", {
                method: "POST",
                body: formData,
              })
                      .then((response) => {
                        console.log("响应状态:", response.status);
                        console.log("响应头:", [...response.headers.entries()]);
                        return response.json();
                      })
                      .then((data) => {
                        console.log("响应数据:", data);
                        if (data.success) {
                          // 检查用户类型是否需要更新
                          if (data.user.usertype && data.user.usertype !== userType) {
                            // 如果数据库中的用户类型与选择的不同，发送更新请求
                            return fetch("/api/updateUserType", {
                              method: "POST",
                              headers: {
                                "Content-Type": "application/x-www-form-urlencoded",
                              },
                              body: `userId=${data.user.id}&newUserType=${userType}`,
                            }).then((response) => response.json());
                          }
                          return data;
                        } else {
                          throw new Error(data.message || "登录失败，请检查账号和密码");
                        }
                      })
                      .then((data) => {
                        if (data.success) {
                          // 登录成功，存储用户信息到本地存储
                          localStorage.setItem("user", JSON.stringify(data.user));
                          // 使用加密后的ID进行跳转
                          window.location.href = `/user/${data.encryptedId}/requirements`;
                        } else {
                          showNotification(data.message || "用户类型更新失败", "error");
                        }
                      })
                      .catch((error) => {
                        showNotification(
                                error.message || "登录请求出错，请稍后再试",
                                "error"
                        );
                      });
            }
          });

  // 添加显示通知的函数
  function showNotification(message, type = "success") {
    const notification = document.querySelector(".notification");
    const messageElement = notification.querySelector(".message");
    const iconElement = notification.querySelector(".icon");

    // 设置消息内容和类型
    messageElement.textContent = message;
    notification.className = "notification";
    if (type === "error") {
      notification.classList.add("error");
      iconElement.textContent = "✕";
    } else {
      iconElement.textContent = "✓";
    }

    // 显示通知
    notification.classList.add("show");

    // 3秒后自动隐藏
    setTimeout(() => {
      notification.classList.remove("show");
    }, 3000);
  }


  let selectedInterests = [];

  // 专家选项点击事件
  document.getElementById('expertOption').addEventListener('click', function() {
    // 选中专家选项
    selectExpertOption();

    // 调用API获取兴趣点
    fetchInterestTopics();
  });

  // 选中专家选项
  function selectExpertOption() {
    const expertDot = document.getElementById('expertDot');
    const expertOption = document.getElementById('expertOption');

    // 添加选中样式
    expertDot.classList.add('selected');
    expertOption.classList.add('border-blue-500');

    console.log('已选择专家用户类型');
  }

  // 获取兴趣点数据
  async function fetchInterestTopics() {
    const loadingState = document.getElementById('loadingState');
    const interestContainer = document.getElementById('interestTopicContainer');

    try {
      // 显示加载状态
      loadingState.classList.remove('hidden');
      interestContainer.classList.add('hidden');

      // 调用API
      const response = await fetch('http://localhost:8080/api/interest-topic', {
        method: 'GET',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
          'Origin': '*'
        }
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();

      // 检查是否有错误
      if (data.error) {
        throw new Error(data.error);
      }

      // 渲染兴趣点
      renderInterestTopics(data.interests);

    } catch (error) {
      console.error('获取兴趣点失败:', error);
      alert('获取兴趣点失败: ' + error.message);
    } finally {
      // 隐藏加载状态
      loadingState.classList.add('hidden');
    }
  }

  // 渲染兴趣点选项
  function renderInterestTopics(interests) {
    const interestList = document.getElementById('interestTopicList');
    const interestContainer = document.getElementById('interestTopicContainer');

    // 清空现有内容
    interestList.innerHTML = '';

    // 生成兴趣点选项
    interests.forEach(interest => {
      const interestItem = document.createElement('div');
      interestItem.className = 'interest-item p-3 border border-gray-200 rounded-lg cursor-pointer hover:border-blue-500 hover:bg-blue-50 transition-all';
      interestItem.dataset.id = interest.id;
      interestItem.innerHTML = `
      <div class="flex items-center justify-between">
        <span class="text-sm font-medium text-gray-900">${interest.interest_topic}</span>
        <div class="w-4 h-4 border border-gray-300 rounded-sm flex items-center justify-center">
          <i class="fa-solid fa-check text-blue-500 text-xs hidden"></i>
        </div>
      </div>
    `;

      // 添加点击事件
      interestItem.addEventListener('click', function() {
        toggleInterestSelection(this, interest);
      });

      interestList.appendChild(interestItem);
    });

    // 显示兴趣点容器
    interestContainer.classList.remove('hidden');

    console.log('兴趣点渲染完成，共', interests.length, '个选项');
  }

  // 切换兴趣点选择状态
  function toggleInterestSelection(element, interest) {
    const checkbox = element.querySelector('i');
    const isSelected = element.classList.contains('selected');

    if (isSelected) {
      // 取消选择
      element.classList.remove('selected', 'border-blue-500', 'bg-blue-50');
      checkbox.classList.add('hidden');
      selectedInterests = selectedInterests.filter(item => item.id !== interest.id);
    } else {
      // 选择
      element.classList.add('selected', 'border-blue-500', 'bg-blue-50');
      checkbox.classList.remove('hidden');
      selectedInterests.push(interest);
    }

    console.log('当前选中的兴趣点:', selectedInterests);
  }

  // 确认选择按钮事件
  document.getElementById('confirmSelection').addEventListener('click', function() {
    if (selectedInterests.length === 0) {
      alert('请至少选择一个兴趣点');
      return;
    }

    console.log('确认选择的兴趣点:', selectedInterests);
    alert('已选择 ' + selectedInterests.length + ' 个兴趣点:\n' +
            selectedInterests.map(item => item.interest_topic).join('\n'));

    // 这里可以添加提交到后端的逻辑
    // submitSelectedInterests(selectedInterests);
  });

  // 提交选中的兴趣点到后端（可选），TODO：用户选择兴趣点之后对应的逻辑待完善
  function submitSelectedInterests(interests) {
    // 这里添加提交逻辑
    console.log('提交兴趣点到后端:', interests);
  }
</script>
</body>
</html>
